package com.atguigu.crowd.mvc.handler;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crowd.entity.Auth;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.service.api.AuthService;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.sun.tools.internal.xjc.generator.bean.ImplStructureStrategy.Result;

@Controller
public class AssignHandler {

	@Autowired
	private AuthService authService;
	
	@Autowired
	private AdminService adminService;
	
	@Autowired
	private RoleService roleService;
	
	//分配权限
	@ResponseBody
	@RequestMapping("/assign/do/role/assign/auth.json")
	public ResultEntity<String> saveRoleAuthRelationship(
			@RequestBody Map<String, List<Integer>> map
			){
		authService.saveRoleAuthRelationship(map);
		return ResultEntity.successWithoutData();
	}
	
	@ResponseBody
	@RequestMapping("/assign/get/assigned/auth/id/by/role/id.json")
	public ResultEntity<List<Integer>> getAssignAuthIdByRoleId(@RequestParam("roleId") Integer roleId){
		List<Integer> authIdList = authService.getAssignAuthIdByRoleId(roleId);
		return ResultEntity.successWithData(authIdList);
	}
	
	@ResponseBody
	@RequestMapping("/assign/get/all/auth.json")
	public ResultEntity<List<Auth>> getAllAuth(){
		List<Auth> authList = authService.getAllAuth();
		
		return ResultEntity.successWithData(authList);
	}
	//跳转分配角色页面
	@RequestMapping("/assign/to/assign/role/page.html")
	public String toAssignRolePage(
			@RequestParam("adminId") Integer adminId,
			ModelMap map
			) {
		List<Role> assignRoleList = roleService.getAssignRole(adminId);
		List<Role> unAssignRoleList = roleService.getUnAssignRole(adminId);
		map.addAttribute("assignRoleList", assignRoleList);
		map.addAttribute("unAssignRoleList", unAssignRoleList);
		return "assign-role";
	}
	//分配角色
	@RequestMapping("/assign/do/role/assign.html")
	public String saveAdminRoleRelatinship(
			@RequestParam("adminId") Integer adminId,
			@RequestParam("pageNum") Integer pageNum,
			@RequestParam("keyword") String keyword,
			// 我们允许用户在页面上取消所有已分配角色再提交表单，所以可以不提供roleIdList请求参数
			// 设置required=false表示这个请求参数不是必须的
			@RequestParam(value="roleIdList", required=false) List<Integer> roleIdList
			){
		adminService.saveAdminRoleRelatinship(adminId,roleIdList);
		
		return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
	}
}
